<?php

namespace app\home\controller;

use think\App;
use think\facade\Db;

class UserTopic extends Common
{
    //线上课程中心
    public function onlineTopic()
    {
        $data1 = Db::name('user_online_topic')->where(['uid' => $this->user['id']])->group('sid,sid_title')->field('sid,sid_title')->select()->toArray();
        $data = Db::name('user_online_topic')->where(['uid' => $this->user['id']])->select()->toArray();
        foreach ($data1 as $k => $v) {
            $i = 0;
            foreach ($data as $k1 => $v1) {
                if ($v['sid'] == $v1['sid']) {
                    $list[$v['sid_title']][$i] = [
                        'id' => $v1['id'],
                        'cid_title' => ($k + 1) . '.' . $v1['cid_title'],
                        'status' => $v1['status'],
                        'learn_times' => $v1['learn_times']

                    ];
                    $list[$v1['sid_title']][$i]['imgcontent'] = strpos($v1['video_images'], '.mp4') !== false ? '看视频' : '图文';
                    $i++;
                }
            }
        }
        return outputJson(1000, 'ok', ['data' => $list]);
    }

    //线上课程详情
    public function onlineTopicDetail()
    {
        $table = input('type') == 1 ? "user_online_topic" : "user_offline_topic";
        $data = Db::name($table)->field('id,cid_title,video_images,content')->where(['id' => input('id')])->find();
        return outputJson(1000, 'ok', ['data' => $data]);
    }

    //线上学习时长
    public function userLearnTime()
    {
        $post = input('post.');
        $data = [
            'uid' => $this->user['id'],
            'upid' => $post['id'],
            'learn_time' => $post['learn_time'],
            'type' => $post['type'],
            'create_time' => date('Y-m-d H:i:s'),
            'add_time' => date('Y-m-d'),
        ];
        $data['upid_title'] = $post['type'] == 1 ? Db::name('user_online_topic')->where(['id' => $post['id']])->value('cid_title'):Db::name('user_offline_topic')->where(['id' => $post['id']])->value('cid_title');
        $tables = $post['type'] == 1 ? 'user_online_topic' : 'user_offline_topic';
        Db::name($tables)->where(['id' => $post['id']])->inc('learn_times', $post['learn_time'])->update();
        Db::name('user_learn_time')->insert($data);
        return outputJson(1000, 'ok');
    }

    //分配课程
    public function allotCourse()
    {
        //type=1 线上 type=2  线下
        if (input('type') == 1) {
            $table1 = "user_online_topic";
            $table2 = "user_online_wrong_topic";
            $table3 = "topics";
            $table4 = "user_online_subject";
        } else {
            $table1 = "user_offline_topic";
            $table2 = "user_offline_wrong_topic";
            $table3 = "offline_topics";
            $table4 = "user_offline_subject";
        }
        //分配课程的id
        $id = input('id');
        //查询科目分类id
        $cource = Db::name($table1)->where(['id' => input('id')])->field('sid,cid,rand_num')->find();
        //查询错题集
        $wrongTopic = Db::name($table2)->where(['uid' => $this->user['id'], 'upid' => $id])->column('tid');
        //排除错题集
        $notid = $wrongTopic ? implode(',', $wrongTopic) : '';
        $where['sid'] = $cource['sid'];
        $where['cid'] = $cource['cid'];
        $topic = Db::name($table3)->where($where)->whereNotIn('id', $notid)->field('id,sid,cid,title,type,images,options,answers,analysis')->select()->toArray();
        if ($wrongTopic && !$topic) {
            //排除已选择的
            $pxcurrentNum = Db::name($table4)->where(['uid' => $this->user['id'], 'upid' => input('id')])->column('id');
            //如果错题集存在，题库不存在，则取错题集
            $notid = $wrongTopic ? implode(',', array_diff($wrongTopic, $pxcurrentNum)) : '';
            $where['sid'] = $cource['sid'];
            $where['cid'] = $cource['cid'];
            $topic = Db::name($table3)->where($where)->whereIn('id', $notid)->field('id,title,type,images,options,answers,analysis')->select()->toArray();
        }
        shuffle($topic);//打乱数组
        //查询完成几道题了
        $currentNum = Db::name($table4)->where(['uid' => $this->user['id'], 'upid' => input('id')])->count();
        $data = array_slice($topic, 0, ($cource['rand_num'] - $currentNum));
        foreach ($data as $k => $v) {
            $data[$k]['options'] = json_decode($v['options'], true);
            $data[$k]['answers'] = array_filter(explode('.', trim(chunk_split($v['answers'], 1, '.'))));
        }
        return outputJson(1000, 'ok', $data);
    }

    //记录正确答案upid即user_online_topic表的id ，tid即topic表的id
    public function referCorrectAnswer()
    {
        $post = input('post.');
        //type=1 线上 type=2  线下
        if ($post['type'] == 1) {
            $table1 = "topics";
            $table2 = "user_online_subject";
            $table3 = "user_online_topic";
        } else {
            $table1 = "offline_topics";
            $table2 = "user_offline_subject";
            $table3 = "user_offline_topic";
        }
        $topic = Db::name($table1)->where(['id' => $post['tid']])->field('id,sid,cid,title,type,images,options,answers,analysis')->find();
        $topicData = [
            'uid' => $this->user['id'],
            'sid' => $topic['sid'],
            'cid' => $topic['cid'],
            'tid' => $post['tid'],
            'upid' => $post['upid'],
            'title' => $topic['title'],
            'type' => $topic['type'],
            'images' => $topic['images'],
            'options' => $topic['options'],
            'answers' => $topic['answers'],
            'analysis' => $topic['analysis'],
            'correct_answer' => $post['correct_answer']
        ];
        $data = Db::name($table2)->where(['uid' => $this->user['id'], 'tid' => $post['tid'], 'upid' => $post['upid']])->find();
        if ($data) {
            return outputJson(1001, '答案已提交，请勿重复提交');
        }
        $result = Db::name($table2)->insert($topicData);
        if (!$result) {
            return outputJson(1001, 'fail');
        }
        //已学习的题目数
        $correctNum = Db::name($table2)->where(['uid' => $this->user['id'], 'upid' => $post['upid']])->count();
        //查找随机题目
        $randNum = Db::name($table3)->where(['uid' => $this->user['id'], 'id' => $post['upid']])->field('wrong_num,rand_num,score')->find();
        //当前课程已学习完
        if ($correctNum == $randNum['rand_num']) {
            //计算分数
            $correctScore = $randNum['score'] - $randNum['wrong_num'];
            $res = Db::name($table3)->where(['uid' => $this->user['id'], 'id' => $post['upid']])->update(['status' => 1, 'correct_score' => $correctScore > 0 ? $correctScore : 0]);
            if ($res === false) {
                return outputJson(1001, 'fail');
            }
        }
        //判断考核是否全部通过
        $onlineTopicNum = Db::name('user_online_topic')->where(['uid' => $this->user['id'], 'id' => $post['upid'], 'status' => 0])->count();
        $offlineTopicNum = Db::name('user_offline_topic')->where(['uid' => $this->user['id'], 'id' => $post['upid'], 'status' => 0])->count();
        if (!$onlineTopicNum && !$offlineTopicNum) {
            return outputJson(1003, '全部考核通过');
        }
        return outputJson(1000, 'ok');
    }

    //答案错误
    public function referWrongAnswer()
    {
        $post = input('post.');
        //type=1 线上 type=2  线下
        if ($post['type'] == 1) {
            $table1 = "topics";
            $table2 = "user_online_wrong_topic";
            $table3 = "user_online_topic";
        } else {
            $table1 = "offline_topics";
            $table2 = "user_offline_wrong_topic";
            $table3 = "user_offline_topic";
        }
        $topic = Db::name($table1)->where(['id' => $post['tid']])->field('id,sid,cid,title,type,images,options,answers,analysis')->find();
        $topicData = [
            'uid' => $this->user['id'],
            'sid' => $topic['sid'],
            'cid' => $topic['cid'],
            'tid' => $post['tid'],
            'upid' => $post['upid'],
            'title' => $topic['title'],
            'type' => $topic['type'],
            'images' => $topic['images'],
            'options' => $topic['options'],
            'answers' => $topic['answers'],
            'analysis' => $topic['analysis'],
            'correct_answer' => $post['correct_answer']
        ];
        $data = Db::name($table2)->where(['uid' => $this->user['id'], 'tid' => $post['tid'], 'upid' => $post['upid']])->find();
        $result = 1;
        if ($data) {
            $result = Db::name($table2)->insert($topicData);
        }

        $res = Db::name($table3)->where(['uid' => $this->user['id'], 'id' => $post['upid']])->inc('wrong_num', 1)->update();
        if (!$result || $res === false) {
            return outputJson(1001, 'fail');
        }
        return outputJson(1000, 'ok');
    }


    //实操课程中心
    public function offlineTopic()
    {
        $data1 = Db::name('user_offline_topic')->where(['uid' => $this->user['id']])->group('sid,sid_title')->field('sid,sid_title')->select()->toArray();
        $data = Db::name('user_offline_topic')->where(['uid' => $this->user['id']])->select()->toArray();
        foreach ($data1 as $k => $v) {
            $i = 0;
            foreach ($data as $k1 => $v1) {
                if ($v['sid'] == $v1['sid']) {
                    $list[$v['sid_title']][$i] = [
                        'id' => $v1['id'],
                        'cid_title' => ($k + 1) . '.' . $v1['cid_title'],
                    ];
                    $i++;
                }
            }
        }
        return outputJson(1000, 'ok', ['data' => $list]);
    }
}